/*
 * 用法示例：
 * layui.YsMultyFile.init({id: 'xxxx', sourceId: 'aaa', sourceType: 'bbb', sourceCode: 'ccc', btnDisable: false});
 */
layui.define(function (exports) {
	var object = {
			c: {data:[]}, // 配置项
			f: function (c) { // 数据初始化
				var s = new Date().getTime();
				var t = this;
				
				if (!c.id) {
					alert('未配置元素ID');
					return;
				}
				if (!c.sourceId) {
					alert('未配置来源ID');
					return;
				}
				if (!c.sourceType) {
					alert('未配置来源类型');
					return;
				}
				if (!c.sourceCode) {
					alert('未配置来源编码');
					return;
				}
				t.c = c;
				t.c.urlUpload = 'https://file.mini-ease.com/api/outer/upload/uploadForERP_1_0';
			},
			load:function () { // 添加监听-多文件框
				var t = this;
				
				// 初始化多文件上传控件
				$('#' + t.c.id).on('click',function (e) {
					var dom = this;
					
					var sourceId = t.c.sourceId;
					var sourceType = t.c.sourceType;
					var sourceCode = t.c.sourceCode;
					var where = {
							sourceId: sourceId,
							sourceType: sourceType,
							sourceCode: sourceCode
						}
					if (sourceId == 'undefined' || sourceId == null || sourceId == 'null') {
						alert('表单尚未保存，无法操作上传');
						return;
					}
					
					t.c.id_modal_multy_file_panel = 'id_modal_multy_file_panel_' + (new Date().getTime()); // 生成容器ID
					t.c.id_modal_multy_file_grid = 'id_modal_multy_file_grid_' + (new Date().getTime()); // 生成表格ID
					var content = 
						`<div class="ysui-col" style="width: 100%;" id="` + t.c.id_modal_multy_file_panel + `">`
							+ `<table class="layui-hide" id="` + t.c.id_modal_multy_file_grid + `" lay-filter="` + t.c.id_modal_multy_file_grid + `"></table>`
							+ `<script type="text/html" id="templet_index_no">`
								+ `{{d.LAY_TABLE_INDEX+1}}`
							+ `</script>`
							+ `<script type="text/html" id="_multy_file_grid_toolbar">`
							+ `<div class="layui-btn-container">`
								+ `<a class="layui-btn layui-btn-normal layui-btn-sm ` + (t.c.btnDisable ? `layui-btn-disabled` : ``) + `" ` + (t.c.btnDisable ? `` : `lay-event="_multy_file_to_add"`) + `><i class="iconfont icon-add-btn"></i>新增</a>`
								+ `<a class="layui-btn layui-btn-normal layui-btn-sm layui-btn-danger ` + (t.c.btnDisable ? `layui-btn-disabled` : ``) + `" ` + (t.c.btnDisable ? `` : `lay-event="_multy_file_batch_delete"`) + `><i class="iconfont icon-delete"></i>删除</a>`
							+ `</div>`
							+ `</script>`
							+ `<script type="text/html" id="templet_script_for_multy_file">`
							+ `<a class="layui-btn layui-btn-xs layui-btn-normal ` + (t.c.btnDisable ? `layui-btn-disabled` : ``) + `" ` + (t.c.btnDisable ? `` : `lay-event="_multy_file_single_download"`) + `><i class="layui-icon layui-icon-download-circle" title="下载"></i></a>`
							+ `<a class="layui-btn layui-btn-xs layui-btn-danger ` + (t.c.btnDisable ? `layui-btn-disabled` : ``) + `" ` + (t.c.btnDisable ? `` : `lay-event="_multy_file_single_delete"`) + `><i class="layui-icon layui-icon-close" title="删除"></i></a>`
							+ `</script>`
						+ `</div>`;
						// + t.loadScriptTPL();
					
					var w=($(window).width()*0.8);
					var h=($(window).height() - 50);
					layer.open({
						type: 1,
						area: [w + 'px', h + 'px'],
						fix: false,
						//不固定
						maxmin: true,
						shade: 0.6,
						title: '附件列表',
						content: content,
						btn: ['确定', '关闭'],
						//点击弹层外区域关闭
						shadeClose: true,
	            		yes: function (index) {// 点击“确定”，执行的回调函数
							layer.close(index);
	            		},
						btn2: function(index, layero){
							layer.close(index);
						},
						success: function(layero, index) {
							layui
							.use(['form', 'table'], function(){
								var table = layui.table;
								var form = layui.form;
								var $ = layui.jquery;
								
								// 创建渲染实例
								table.render({
									elem: '#' + t.c.id_modal_multy_file_grid
									,url: '/api/inter/tbFileInfo/search'
									,toolbar: '#_multy_file_grid_toolbar'
									,defaultToolbar: [{
											title: '刷新页面'
											,layEvent: 'LAYTABLE_REFRESH'
											,icon: 'layui-icon-refresh'
										}]
									,height: 'full-240' // 最大高度减去其他容器已占有的高度差
									,limit : 50
									,limits : [50,100,200,500]
									,where: where
									,cellMinWidth: 150
									,page: true
									,request: {
										pageName: 'page',
										limitName: 'size'
									}
									,even: false // 开启隔行背景
									,cols: [ [
							          	{'title': '', 'type': 'checkbox', 'fixed': 'left', 'unresize': true, 'width': '70'},
									    {'title': '文件名', 'field': 'preName', 'width': '180', 'align': 'center'},
									    {'title': '大小', 'field': 'fileSize', 'width': '80', 'align': 'center'},
									    {'title': '类型', 'field': 'sufName', 'width': '120', 'align': 'center'},
									    {'title': '上传时间', 'field': 'createTime', 'width': '200', 'align': 'center'},
									    {'title': '操作', 'field': 'ope', 'width': '240', 'align': 'center', templet: '#templet_script_for_multy_file'}
								    ] ]
									,done: function(objDone){
										$(dom).val(objDone.count + '个附件');
										
										// 绑定新增按钮-文件上传控件
										$('#' + t.c.id_modal_multy_file_panel).find('a[lay-event="_multy_file_to_add"]').each(function(index, domEle){
											var dom = this;
											var labelName = $(this).attr('label');
											layui.upload.render({
												elem: dom,
												url: t.c.urlUpload,
												multiple: true,
												accept: 'file',
												progress: function(n, elem){
													//dom.val(n + '%');
												},
												done: function(res, index, upload){
													if (res.code == 0) {
														console.log(res);
														var fileName = res.data.fileName;
														var indexPeriod = fileName.indexOf('.');
														
														// 添加数据到附件表
														$.ajax({
															type: "POST",
															url: '/api/inter/tbFileInfo/add',
															data: {
																sourceType: sourceType,
																sourceId: sourceId,
																sourceCode: sourceCode,
																preName: indexPeriod >= 0 ? fileName.substring(0, indexPeriod) : fileName,
																sufName: indexPeriod >= 0 ? fileName.substring(indexPeriod + 1, fileName.length) : '',
																fileType: res.data.fileType,
																fileSize: res.data.fileSizeLong,
																filePath: res.data.filePath
															},
															success: function (data) {
																if (data.code == 0) {
																} else {
																	alert(data.msg);
																}
															}
														});
														return;
													}
												},
												allDone: function(obj){
													setTimeout(function(){
														layui.table.reload(t.c.id_modal_multy_file_grid, {
															page: {curr: 1},
															where: where
														});
													}, 1000);
												}
											});
										});
									}
									,error: function(res, msg){
										console.log(res, msg)
									}
								});
							});

							// 右侧工具栏事件
							layui.table.on('toolbar(' + t.c.id_modal_multy_file_grid + ')', function(obj){
								var id = obj.config.id;
								var checkStatus = layui.table.checkStatus(id);
								var datas = checkStatus.data;
								var othis = lay(this);

								switch(obj.event){
									case '_multy_file_batch_delete':
									{
										if(datas.length == 0) {
											layer.alert('尚未选中数据');
										} else {
											var ids = '';
											for(var i = 0 ;i < datas.length; i++){
												ids += datas[i].id + ',';
											}
											var indexOfLoading = layer.load(1, {
												shade: [0.5,'#000000'] //0.1透明度的白色背景
											});
											$.ajax({
												type: "POST",
												url: '/api/inter/tbFileInfo/deleteBatch',
												data: {ids: ids.substring(0, ids.length - 1)},
												success: function (res) {
													if (res.code == 0) {
														layer.msg(res.msg);
														layui.table.reload(t.c.id_modal_multy_file_grid,{
															page: {curr: 1},
															where: where
														})
													} else {
														alert(res.msg);
													}
													layer.close(indexOfLoading);
												}
											});
										}
										break;
									}
								};
							});

							// 表格内按钮点击事件
							layui.table.on('tool(' + t.c.id_modal_multy_file_grid + ')', function(obj){
								console.log(obj);
								switch(obj.event){
									case '_multy_file_single_download':
									{
										const xhr = new XMLHttpRequest();
										xhr.open('GET', obj.data.filePath);
										xhr.responseType = 'blob';
										xhr.onload = function() {
											const blob = xhr.response;
											const link = document.createElement('a');
											link.href = URL.createObjectURL(blob);
											link.download = obj.data.preName + (obj.data.sufName ? '.' + obj.data.sufName : '');
											link.target = "_blank"; // 可选，如果希望在新窗口中下载文件，请取消注释此行
											link.click();
										};
										xhr.send();
										layer.close(indexOfLoading);
										break;
									}
									case '_multy_file_single_delete':
									{
										layer.confirm('确定删除此附件？ ', {
											btn: ['确定','取消'] //按钮
										}, function(index){
											var indexOfLoading = layer.load(1, {
												shade: [0.5,'#000000'] //0.1透明度的白色背景
											});
											$.ajax({
												type: "POST",
												url: '/api/inter/tbFileInfo/delete',
												data: {id: obj.data.id},
												success: function (res) {
													if (res.code == 0) {
														layer.msg(res.msg);
														layui.table.reload(t.c.id_modal_multy_file_grid,{
															page: {curr: 1},
															where: where
														})
													} else {
														alert(res.msg);
													}
													layer.close(indexOfLoading);
												}
											});
										}, function(index){
											layer.close(index);
										});
										break;
									}
								};
							});
						}
					});
				});
			},
			init:function (c) {
				this.f(c);
				this.load();
				return object;
			}
		};
	exports('YsMultyFile', object);
});